package org.mspring.mlog.service;

import org.apache.commons.lang3.StringUtils;
import org.mspring.mlog.cache.UserCacheService;
import org.mspring.mlog.dao.UserEntityDao;
import org.mspring.mlog.entity.UserEntity;
import org.mspring.nbee.common.PageResult;
import org.mspring.nbee.db.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.db.dao.sql.pager.SqlPager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2014-09-10 12:44:49
 */
@Service
public class UserEntityService {

    private static final Logger LOG = LoggerFactory.getLogger(UserEntityService.class);

    private UserEntityDao userEntityDao;
    private UserCacheService userCacheService;

    @Transactional
    public boolean update(UserEntity user) {
        boolean flag = userEntityDao.update(user);
        if (flag) {
            userCacheService.invalidate(user.getUsername());
        }
        return flag;
    }

    @Transactional
    public boolean deleteById(long id) {
        UserEntity user = userEntityDao.findById(id);
        if (user == null) {
            return true;
        }
        boolean flag = userEntityDao.deleteById(id);
        if (flag) {
            userCacheService.invalidate(user.getUsername());
        }
        return flag;
    }

    public UserEntity findById(long id) {
        return userEntityDao.findById(id);
    }

    public PageResult<UserEntity> list(List<SqlCondition> conditions, SqlPager pager) {
        return userEntityDao.listPage(conditions, pager);
    }

    @Autowired
    public void setUserEntityDao(UserEntityDao userEntityDao) {
        this.userEntityDao = userEntityDao;
    }

    @Autowired
    public void setUserCacheService(UserCacheService userCacheService) {
        this.userCacheService = userCacheService;
    }
}
